package cn.boysoft.core.server.netty.codec;

import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.boysoft.core.model.message.xml.XMLResponse;
import cn.boysoft.core.util.XmlUtil;
/**
 * @author 付厚俊
 * CreateTime 2013-4-4 下午5:09:32
 */
@Service(value="xmlResponseEncoder")
public class XmlResponseEncoder extends OneToOneEncoder{
	private final static Logger LOGGER = LoggerFactory.getLogger(XmlResponseEncoder.class);
	@Override
	protected Object encode(ChannelHandlerContext context, Channel channel,
			Object object) throws Exception {
		
		if (object instanceof XMLResponse) {
			XMLResponse xmlResponse = (XMLResponse)object;
			String content = xmlResponse.toXml();
			LOGGER.debug("XMLResponse :\r\n"+XmlUtil.formatXml(content));
			HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
			response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
			response.setContent(ChannelBuffers.copiedBuffer(content, CharsetUtil.UTF_8));
			response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
			LOGGER.debug("HttpResponse :\r\n"+response.toString());
            return response;
        }
		return object;
	}

}
